import { ref } from 'vue'
import type { RequestWrapper } from '@/core/interfaces/common'
import { createRequest } from '@/core/api/request'

// 为了兼容性，定义 BaseResponse 类型别名
type BaseResponse<T> = RequestWrapper<T>

// 用户信息数据结构
export interface UserInfoItem {
  userName: string
  createTime: string
}

// 请求参数类型
export interface UserInfoParams {
  orderId: string | number // 经过Base64编码的订单ID
}

const request = createRequest()

export const getUserInfo = (params: UserInfoParams) => {
  return request<BaseResponse<UserInfoItem[]>>({
    url: '/api/v1/analysis/keyword/user-info',
    method: 'GET',
    params
  })
}

// 兼容项目现有风格的API调用方式
export default function useUserInfoAPI() {
  const response = ref<BaseResponse<UserInfoItem[]> | null>(null)
  const loading = ref(false)
  const error = ref<Error | null>(null)

  const setLoading = (state: boolean) => {
    loading.value = state
  }

  const setError = (err: Error | null) => {
    error.value = err
  }

  const setResponse = (res: BaseResponse<UserInfoItem[]>) => {
    response.value = res
  }

  const fetch = async (params: UserInfoParams) => {
    try {
      setLoading(true)
      setError(null)
      const result = await getUserInfo(params)
      setResponse(result)
      return [null, result] as const
    } catch (err) {
      const error = err as Error
      setError(error)
      return [error, null] as const
    } finally {
      setLoading(false)
    }
  }

  return [response, fetch, loading, error] as const
}
